package com.triones.api.service.third;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.InterlaceConfig;
import com.ruoyi.common.constant.InterlaceApiPathConstants;
import com.ruoyi.common.constant.InterlaceOauthKeyConstants;
import com.ruoyi.common.utils.InterlaceUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.triones.api.entity.interlace.bo.request.*;
import com.triones.api.entity.interlace.dto.*;
import com.triones.api.entity.interlace.vo.InterlaceCryptoWalletVO;
import com.triones.api.entity.interlace.vo.InterlaceMemberVO;
import com.triones.api.mapper.interlace.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * interlace 接口（调用第三方）业务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InterlaceServiceImpl implements InterlaceService {

    private final InterlaceConfig interlaceConfig;

    private final MasterBalanceMapper masterBalanceMapper;

    private final MasterCryptoWalletMapper masterCryptoWalletMapper;

    private final OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(15, TimeUnit.SECONDS)
        .build();

    @Override
    public Map oauthAuthorize() {
        OauthAuthorizeRequest request = new OauthAuthorizeRequest();
        request.setClientId(interlaceConfig.getClientId());
        return this.sendNotTokenGet(InterlaceApiPathConstants.oauth_authorize, request, null);
    }

    @Override
    public void oauthAccessToken() {
        Map map = this.oauthAuthorize();
        if (map != null) {
            String code = (String) map.get("code");
            OauthAccessTokenRequest request = new OauthAccessTokenRequest();
            request.setClientId(interlaceConfig.getClientId());
            request.setClientSecret(interlaceConfig.getClientSecret());
            request.setCode(code);
            Map response = this.sendNotTokenPost(InterlaceApiPathConstants.oauth_access_token, request, null);
            if (response != null) {
                RedisUtils.setCacheObject(InterlaceOauthKeyConstants.ACCESS_TOKEN, response.get("accessToken"),
                    Duration.ofSeconds(Convert.toLong(response.get("expiresIn"))));
                RedisUtils.setCacheObject(InterlaceOauthKeyConstants.REFRESH_TOKEN, response.get("refreshToken"),
                    Duration.ofSeconds(interlaceConfig.getRefreshTokenExpiresIn()));
            }
        }
    }

    @Override
    public void oauthRefreshToken() {
        OauthRefreshTokenRequest request = new OauthRefreshTokenRequest();
        request.setClientId(interlaceConfig.getClientId());
        long refreshTokenExpiresIn = RedisUtils.getTimeToLive(InterlaceOauthKeyConstants.REFRESH_TOKEN);
        if (refreshTokenExpiresIn <= 0) {
            this.oauthAccessToken();
        } else {
            request.setRefreshToken(RedisUtils.getCacheObject(InterlaceOauthKeyConstants.REFRESH_TOKEN));
            Map response = this.sendNotTokenPost(InterlaceApiPathConstants.oauth_refresh_token, request, null);
            if (response != null) {
                RedisUtils.setCacheObject(InterlaceOauthKeyConstants.ACCESS_TOKEN, response.get("accessToken"),
                    Duration.ofSeconds(Convert.toLong(response.get("expiresIn"))));
            }
        }
    }

    @Override
    public String getAccessToken() {
        long accessTokenExpiresIn = RedisUtils.getTimeToLive(InterlaceOauthKeyConstants.ACCESS_TOKEN);
        if (accessTokenExpiresIn <= 0) {
            this.oauthRefreshToken();
        }
        String accessToken = RedisUtils.getCacheObject(InterlaceOauthKeyConstants.ACCESS_TOKEN);
        if (accessToken == null || accessToken.isEmpty()) {
            throw new SecurityException("无法获取有效的访问令牌");
        }
        return accessToken;
    }

    @Override
    public Map accountsRegister(AccountsRegisterRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.accounts_register, request, null);
    }

    @Override
    public Map cryptoconnectWallets(CryptoconnectWalletsRequest request) {
        return (Map) this.sendGet(InterlaceApiPathConstants.cryptoconnect_wallets, request, null);
    }

    @Override
    public Map cryptoconnectWalletsAddresses(CryptoconnectWalletsAddressesRequest request, String walletId) {
        Map<String, String> pathParams = new HashMap<>();
        pathParams.put("id", walletId);
        String url = InterlaceApiPathConstants.cryptoconnect_wallets_addresses;
        String finalUrl = InterlaceUtils.replacePathParameters(url, pathParams);
        return (Map) this.sendPost(finalUrl, request, null);
    }

    @Override
    public Map transfersFeeAndQuota(TransfersFeeAndQuotaRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.transfers_fee_and_quota, request, null);
    }

    @Override
    public Map transfers(TransfersRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.transfers, request, null);
    }

    @Override
    public Map triggerWebhook(TriggerWebhookRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.trigger_webhook, request, null);
    }

    @Override
    public Map estimateQuote(EstimateQuoteRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.estimate_quote, request, null);
    }

    @Override
    public String uploadFile(UploadFileRequest request) {
        try {
            List<String> stringList = this.sendUploadFilePost(request.getFile());
            return stringList.get(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("上传文件失败");
    }

    @Override
    public String kyc(KycRequest request, String accountId) {
        KycAddressRequest address = request.getAddress();
        if (address == null) {
            throw new RuntimeException("请填写居住地址信息");
        }
        Map<String, String> pathParams = new HashMap<>();
        pathParams.put("id", accountId);
        String url = InterlaceApiPathConstants.kyc;
        String finalUrl = InterlaceUtils.replacePathParameters(url, pathParams);
        return (String) this.sendPost(finalUrl, request, null);
    }

    @Override
    public Boolean initialization(String accountId) {
        Map<String, String> pathParams = new HashMap<>();
        pathParams.put("id", accountId);
        String url = InterlaceApiPathConstants.initialization;
        String finalUrl = InterlaceUtils.replacePathParameters(url, pathParams);
        return (Boolean) this.sendPost(finalUrl, null, null);
    }

    @Override
    public Map getWallet(String walletId) {
        Map<String, String> pathParams = new HashMap<>();
        pathParams.put("id", walletId);
        String url = InterlaceApiPathConstants.get_wallet;
        String finalUrl = InterlaceUtils.replacePathParameters(url, pathParams);
        return (Map) this.sendGet(finalUrl, null, null);
    }

    @Override
    public Map internalTransferCrypto(InternalTransferRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.asset_transfers, request, null);
    }

    @Override
    public String createCardholder(CreateCardholderRequest request, String accountId) {
        Map<String, String> pathParams = new HashMap<>();
        pathParams.put("accountId", accountId);
        String url = InterlaceApiPathConstants.create_cardholder;
        String finalUrl = InterlaceUtils.replacePathParameters(url, pathParams);
        return (String) this.sendPost(finalUrl, request, null);
    }

    @Override
    public Map infinityCardDetails(String cardId) {
        InfinityCardDetailsRequest request = new InfinityCardDetailsRequest();
        request.setCardId(cardId);
        return (Map) this.sendGet(InterlaceApiPathConstants.infinity_card_details, request, null);
    }

    @Override
    public List<Map> availableCardBINs() {
        return (List<Map>) this.sendGet(InterlaceApiPathConstants.available_card_bins,null,null);
    }

    @Override
    public Map listAllBalances(ListAllBalancesRequest request) {
        return (Map) this.sendGet(InterlaceApiPathConstants.list_all_balances,request,null);
    }

    @Override
    public Map convertTrades(ConvertTradesRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.convert_trades,request,null);
    }

    @Override
    public Map quantumSubAccountToCryptoAssets(QuantumSubAccountToCryptoAssetsRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.asset_transfers,request,null);
    }

    @Override
    public Map cryptoAssetsToQuantumSubAccount(CryptoAssetsToQuantumSubAccountRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.asset_transfers,request,null);
    }

    @Override
    public Map getOnceTransfer(String id) {
        Map<String, String> pathParams = new HashMap<>();
        pathParams.put("id", id);
        String url = InterlaceApiPathConstants.get_transfer;
        String finalUrl = InterlaceUtils.replacePathParameters(url, pathParams);
        return (Map) this.sendGet(finalUrl, null, null);
    }

    @Override
    public String createBudget(CreateBudgetRequest request) {
        return (String) this.sendPost(InterlaceApiPathConstants.create_budget, request, null);
    }

    @Override
    public Map listAllBudgets(ListAllBudgetsRequest request) {
        return (Map) this.sendGet(InterlaceApiPathConstants.list_all_budgets,request,null);
    }

    @Override
    public Boolean createInfinityCardToPrepaid(CreateInfinityCardToPrepaidRequest request) {
        return (Boolean) this.sendPost(InterlaceApiPathConstants.create_infinity_card, request, null);
    }

    @Override
    public Boolean createInfinityCardToBudget(CreateInfinityCardToBudgetRequest request) {
        return (Boolean) this.sendPost(InterlaceApiPathConstants.create_infinity_card, request, null);
    }

    @Override
    public List<Map> physicalCardFees(PhysicalCardFeesRequest request) {
        return (List<Map>) this.sendGet(InterlaceApiPathConstants.physical_card_fees, request, null);
    }

    @Override
    public Boolean bulkShipPhysicalCards(BulkShipPhysicalCardsRequest request) {
        return (Boolean) this.sendPost(InterlaceApiPathConstants.bulk_ship_physical_cards, request, null);
    }

    @Override
    public Map getCard(GetCardRequest request, String cardId) {
        Map<String, String> pathParams = new HashMap<>();
        pathParams.put("id", cardId);
        String url = InterlaceApiPathConstants.get_a_card;
        String finalUrl = InterlaceUtils.replacePathParameters(url, pathParams);
        return (Map) this.sendGet(finalUrl, request, null);
    }

    @Override
    public Boolean infinityCardTransferIn(InfinityCardTransferRequest request) {
        return (Boolean) this.sendPost(InterlaceApiPathConstants.infinity_card_transfer_in, request, null);
    }

    @Override
    public Boolean infinityCardTransferOut(InfinityCardTransferRequest request) {
        return (Boolean) this.sendPost(InterlaceApiPathConstants.infinity_card_transfer_out, request, null);
    }

    @Override
    public Boolean increaseTheBudgetBalance(BudgetChangeRequest request) {
        return (Boolean) this.sendPost(InterlaceApiPathConstants.increase_the_budget_balance, request, null);
    }

    @Override
    public Boolean decreaseTheBudgetBalance(BudgetChangeRequest request) {
        return (Boolean) this.sendPost(InterlaceApiPathConstants.decrease_the_budget_balance, request, null);
    }

    @Override
    public Boolean unfreezeInfinityCard(FreezeInfinityCardRequest request) {
        return (Boolean) this.sendPut(InterlaceApiPathConstants.unfreeze_infinity_card, request, null);
    }

    @Override
    public Boolean freezeInfinityCard(FreezeInfinityCardRequest request) {
        return (Boolean) this.sendPut(InterlaceApiPathConstants.freeze_infinity_card, request, null);
    }

    @Override
    public Map subAccountToMasterAccount(SubAccountToMasterAccountRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.asset_transfers,request,null);
    }

    @Override
    public Map masterAccountToSubAccount(MasterAccountToSubAccountRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.asset_transfers,request,null);
    }

    @Override
    public void initMasterAccountWallet() {
        CryptoconnectWalletsRequest request = new CryptoconnectWalletsRequest();
        request.setMaster(true);
        request.setAccountId(interlaceConfig.getMasterAccount());
        request.setLimit("50");
        request.setPage("0");
        Map map = this.cryptoconnectWallets(request);
        if (map != null) {
            List<Map> wallets = (List<Map>) map.get("data");
            if (wallets != null && wallets.size() > 0) {
                for (Map wallet : wallets) {
                    String walletId = Convert.toStr(wallet.get("id"));
                    MasterCryptoWalletDO masterCryptoWallet = masterCryptoWalletMapper.selectOne(new LambdaQueryWrapper<MasterCryptoWalletDO>()
                        .eq(MasterCryptoWalletDO::getWalletId, walletId)
                        .eq(MasterCryptoWalletDO::getAccountId, interlaceConfig.getMasterAccount()));
                    if (masterCryptoWallet == null) {
                        masterCryptoWallet = new MasterCryptoWalletDO();
                        masterCryptoWallet.setUid(interlaceConfig.getMasterMemberId());
                        masterCryptoWallet.setAccountId(interlaceConfig.getMasterAccount());
                        masterCryptoWallet.setWalletId(walletId);
                        masterCryptoWallet.setMaster(Convert.toBool(wallet.get("master")) ? 1 : 0);
                        masterCryptoWallet.setCurrency(Convert.toStr(wallet.get("currency")));
                        masterCryptoWallet.setCreateTime(System.currentTimeMillis());
                        masterCryptoWallet.setUpdateTime(System.currentTimeMillis());
                        masterCryptoWalletMapper.insert(masterCryptoWallet);
                    }
                    List<Map> balances = (List<Map>) wallet.get("balances");
                    if (balances != null && balances.size() > 0) {
                        for (Map balance : balances) {
                            MasterBalanceDO masterBalance = masterBalanceMapper.selectOne(new LambdaQueryWrapper<MasterBalanceDO>()
                                .eq(MasterBalanceDO::getBid, balance.get("id"))
                                .eq(MasterBalanceDO::getWalletId, walletId)
                                .eq(MasterBalanceDO::getAccountId, interlaceConfig.getMasterAccount())
                                .last("FOR UPDATE"));
                            if (masterBalance == null) {
                                masterBalance = new MasterBalanceDO();
                                masterBalance.setUid(interlaceConfig.getMasterMemberId());
                                masterBalance.setAccountId(interlaceConfig.getMasterAccount());
                                masterBalance.setWalletId(walletId);
                                masterBalance.setBid(Convert.toStr(balance.get("id")));
                                masterBalance.setCurrency(Convert.toStr(balance.get("currency")));
                                masterBalance.setWalletType(Convert.toStr(wallet.get("walletType")));
                                masterBalance.setAvailable(Convert.toBigDecimal(balance.get("available"),BigDecimal.ZERO));
                                masterBalance.setPending(Convert.toBigDecimal(balance.get("pending"),BigDecimal.ZERO));
                                masterBalance.setFrozen(Convert.toBigDecimal(balance.get("frozen"),BigDecimal.ZERO));
                                masterBalance.setVirtualAvailable(BigDecimal.ZERO);
                                masterBalance.setVirtualPending(BigDecimal.ZERO);
                                masterBalance.setVirtualFrozen(BigDecimal.ZERO);
                                masterBalance.setWaitQuote(BigDecimal.ZERO);
                                masterBalance.setCreateTime(System.currentTimeMillis());
                                masterBalance.setUpdateTime(System.currentTimeMillis());
                                masterBalanceMapper.insert(masterBalance);
                            } else {
                                masterBalance.setAvailable(Convert.toBigDecimal(balance.get("available"),BigDecimal.ZERO));
                                masterBalance.setPending(Convert.toBigDecimal(balance.get("pending"),BigDecimal.ZERO));
                                masterBalance.setFrozen(Convert.toBigDecimal(balance.get("frozen"),BigDecimal.ZERO));
                                masterBalance.setWalletType(Convert.toStr(wallet.get("walletType")));
                                masterBalance.setUpdateTime(System.currentTimeMillis());
                                masterBalanceMapper.updateById(masterBalance);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void initMasterBalance() {
        ListAllBalancesRequest request = new ListAllBalancesRequest();
        request.setAccountId(interlaceConfig.getMasterAccount());
        request.setLimit("50");
        request.setPage("0");
        Map map = this.listAllBalances(request);
        if (map != null) {
            List<Map> data = (List<Map>) map.get("data");
            if (data != null && data.size() > 0) {
                for (Map balance : data) {
                    MasterBalanceDO masterBalance = masterBalanceMapper.selectOne(new LambdaQueryWrapper<MasterBalanceDO>()
                        .eq(MasterBalanceDO::getBid, balance.get("id"))
                        .eq(MasterBalanceDO::getAccountId, interlaceConfig.getMasterAccount())
                        .last("FOR UPDATE"));
                    if (masterBalance == null) {
                        masterBalance = new MasterBalanceDO();
                        masterBalance.setUid(interlaceConfig.getMasterMemberId());
                        masterBalance.setAccountId(interlaceConfig.getMasterAccount());
                        masterBalance.setBid(Convert.toStr(balance.get("id")));
                        masterBalance.setCurrency(Convert.toStr(balance.get("currency")));
                        masterBalance.setAvailable(Convert.toBigDecimal(balance.get("available"),BigDecimal.ZERO));
                        masterBalance.setPending(Convert.toBigDecimal(balance.get("pending"),BigDecimal.ZERO));
                        masterBalance.setFrozen(Convert.toBigDecimal(balance.get("frozen"),BigDecimal.ZERO));
                        masterBalance.setWalletType(Convert.toStr(balance.get("walletType")));
                        masterBalance.setVirtualAvailable(BigDecimal.ZERO);
                        masterBalance.setVirtualPending(BigDecimal.ZERO);
                        masterBalance.setVirtualFrozen(BigDecimal.ZERO);
                        masterBalance.setWaitQuote(BigDecimal.ZERO);
                        masterBalance.setCreateTime(System.currentTimeMillis());
                        masterBalance.setUpdateTime(System.currentTimeMillis());
                        masterBalanceMapper.insert(masterBalance);
                    } else {
                        masterBalance.setAvailable(Convert.toBigDecimal(balance.get("available"),BigDecimal.ZERO));
                        masterBalance.setPending(Convert.toBigDecimal(balance.get("pending"),BigDecimal.ZERO));
                        masterBalance.setFrozen(Convert.toBigDecimal(balance.get("frozen"),BigDecimal.ZERO));
                        masterBalance.setWalletType(Convert.toStr(balance.get("walletType")));
                        masterBalance.setUpdateTime(System.currentTimeMillis());
                        masterBalanceMapper.updateById(masterBalance);
                    }
                }
            }
        }
    }

    @Override
    public Map cryptoToMasterQuantum(CryptoToMasterQuantumRequest request) {
        return (Map) this.sendPost(InterlaceApiPathConstants.asset_transfers, request, null);
    }

    @Override
    public Boolean deleteCard(DeleteCardRequest request) {
        return (Boolean) this.sendDelete(InterlaceApiPathConstants.del_card,request,null);
    }

    @Override
    public Boolean velocityControl(VelocityControlRequest request) {
        return (Boolean) this.sendPut(InterlaceApiPathConstants.velocity_control,request,null);
    }

    /**
     * 发送GET请求
     */
    public Object sendGet(String apiLink, Object obj, String pathParam) {
        String sortAndEncodeParams = InterlaceUtils.sortAndEncodeParams(obj);
        String url = "";
        if (pathParam == null) {
            url = interlaceConfig.getUrl() + apiLink;
        } else {
            url = interlaceConfig.getUrl() + apiLink + pathParam;
        }
        if (sortAndEncodeParams != null && !sortAndEncodeParams.equals("")) {
            url = url + "?" + sortAndEncodeParams;
        }
        log.info("发起GET请求 : {}", url);
        Request request = new Request.Builder()
            .url(url)
            .get()
            .header("x-access-token", this.getAccessToken())
            .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = response.body().string();
                log.info("成功 - 响应参数 : {}", responseBody);
                Map mapResponse = objectMapper.readValue(responseBody, Map.class);
                if (Convert.toStr(mapResponse.get("code")).equals("0") && Convert.toStr(mapResponse.get("message")).equals("ok")) {
                    return mapResponse.get("data");
                } else {
                    log.info("非正常成功 - 响应参数 : {}", responseBody);
                    throw new SecurityException(Convert.toStr(mapResponse.get("message")));
                }
            } else {
                String responseBody = response.body().string();
                log.error("失败 - 响应参数 ：{}", responseBody);
                throw new SecurityException(responseBody);
            }
        } catch (IOException e) {
            log.error("IOException occurred: ", e);
            throw new SecurityException(e.getMessage());
        }
    }

    /**
     * 发送POST请求
     */
    public Object sendPost(String apiLink, Object obj, String pathParam) {
        String objectToJson = InterlaceUtils.convertObjectToJson(obj);
        String contentType = "application/json";
        MediaType mediaType = MediaType.parse(contentType);
        RequestBody body = RequestBody.create(mediaType, objectToJson);
        String url = interlaceConfig.getUrl() + apiLink;
        if (pathParam != null && !pathParam.equals("")) {
            url = url + pathParam;
        }
        Request request = new Request.Builder()
            .url(url)
            .post(body)
            .header("x-access-token", this.getAccessToken())
            .build();
        log.info("发起POST请求 : {},body: {}", url, objectToJson);
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = response.body().string();
                log.info("成功 - 响应参数 : {}", responseBody);
                Map mapResponse = objectMapper.readValue(responseBody, Map.class);
                if (Convert.toStr(mapResponse.get("code")).equals("0") && Convert.toStr(mapResponse.get("message")).equals("ok")) {
                    return mapResponse.get("data");
                } else {
                    log.info("非正常成功 - 响应参数 : {}", responseBody);
                    throw new SecurityException(Convert.toStr(mapResponse.get("message")));
                }
            } else {
                String responseBody = response.body().string();
                log.error("失败 - 响应参数 ：{}", responseBody);
                throw new SecurityException(responseBody);
            }
        } catch (IOException e) {
            log.error("IOException occurred: ", e);
            throw new SecurityException(e.getMessage());
        }
    }

    /**
     * 发送PUT请求
     */
    public Object sendPut(String apiLink, Object obj, String pathParam) {
        String objectToJson = InterlaceUtils.convertObjectToJson(obj);
        String contentType = "application/json";
        MediaType mediaType = MediaType.parse(contentType);
        RequestBody body = RequestBody.create(mediaType, objectToJson);
        String url = interlaceConfig.getUrl() + apiLink;
        if (pathParam != null && !pathParam.equals("")) {
            url = url + pathParam;
        }
        Request request = new Request.Builder()
            .url(url)
            .put(body)
            .header("x-access-token", this.getAccessToken())
            .build();
        log.info("发起PUT请求 : {},body: {}", url, objectToJson);
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = response.body().string();
                log.info("成功 - 响应参数 : {}", responseBody);
                Map mapResponse = objectMapper.readValue(responseBody, Map.class);
                if (Convert.toStr(mapResponse.get("code")).equals("0") && Convert.toStr(mapResponse.get("message")).equals("ok")) {
                    return mapResponse.get("data");
                } else {
                    log.info("非正常成功 - 响应参数 : {}", responseBody);
                    throw new SecurityException(Convert.toStr(mapResponse.get("message")));
                }
            } else {
                String responseBody = response.body().string();
                log.error("失败 - 响应参数 ：{}", responseBody);
                throw new SecurityException(responseBody);
            }
        } catch (IOException e) {
            log.error("IOException occurred: ", e);
            throw new SecurityException(e.getMessage());
        }
    }

    /**
     * 发送DELETE请求
     */
    public Object sendDelete(String apiLink, Object obj, String pathParam) {
        String objectToJson = InterlaceUtils.convertObjectToJson(obj);
        String contentType = "application/json";
        MediaType mediaType = MediaType.parse(contentType);
        RequestBody body = RequestBody.create(mediaType, objectToJson);
        String url = interlaceConfig.getUrl() + apiLink;
        if (pathParam != null && !pathParam.equals("")) {
            url = url + pathParam;
        }
        Request request = new Request.Builder()
            .url(url)
            .delete(body)
            .header("x-access-token", this.getAccessToken())
            .build();
        log.info("发送DELETE请求 : {},body: {}", url, objectToJson);
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = response.body().string();
                log.info("成功 - 响应参数 : {}", responseBody);
                Map mapResponse = objectMapper.readValue(responseBody, Map.class);
                if (Convert.toStr(mapResponse.get("code")).equals("0") && Convert.toStr(mapResponse.get("message")).equals("ok")) {
                    return mapResponse.get("data");
                } else {
                    log.info("非正常成功 - 响应参数 : {}", responseBody);
                    throw new SecurityException(Convert.toStr(mapResponse.get("message")));
                }
            } else {
                String responseBody = response.body().string();
                log.error("失败 - 响应参数 ：{}", responseBody);
                throw new SecurityException(responseBody);
            }
        } catch (IOException e) {
            log.error("IOException occurred: ", e);
            throw new SecurityException(e.getMessage());
        }
    }

    /**
     * 发送文件上传post请求
     *
     * @param file 要上传的文件
     * @return 上传后的文件标识或路径
     */
    public List<String> sendUploadFilePost(MultipartFile file) throws IOException {
        RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("files", file.getOriginalFilename(),
                RequestBody.create(file.getBytes(), MediaType.parse(file.getContentType() != null ? file.getContentType() : "application/octet-stream")))
            .build();
        String url = interlaceConfig.getUrl() + InterlaceApiPathConstants.upload_file;
        Request request = new Request.Builder()
            .url(interlaceConfig.getUrl() + InterlaceApiPathConstants.upload_file) // 使用配置的URL
            .post(requestBody)
            .addHeader("accept", "application/json")
            .addHeader("x-access-token", this.getAccessToken())
            .build();
        log.info("发送文件上传post请求 : {}", url);
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = response.body().string();
                log.info("成功 - 响应参数 : {}", responseBody);
                Map mapResponse = objectMapper.readValue(responseBody, Map.class);
                if (Convert.toStr(mapResponse.get("code")).equals("0") && Convert.toStr(mapResponse.get("message")).equals("ok")) {
                    return (List<String>) mapResponse.get("data");
                } else {
                    log.info("非正常成功 - 响应参数 : {}", responseBody);
                    throw new SecurityException(Convert.toStr(mapResponse.get("message")));
                }
            } else {
                String responseBody = response.body().string();
                log.error("失败 - 响应参数 ：{}", responseBody);
                throw new SecurityException(responseBody);
            }
        } catch (IOException e) {
            log.error("IOException occurred: ", e);
            throw new SecurityException(e.getMessage());
        }
    }

    /**
     * 发送GET请求（不携带token）
     */
    public Map sendNotTokenGet(String apiLink, Object obj, String pathParam) {
        String sortAndEncodeParams = InterlaceUtils.sortAndEncodeParams(obj);
        String url = "";
        if (pathParam == null) {
            url = interlaceConfig.getUrl() + apiLink;
        } else {
            url = interlaceConfig.getUrl() + apiLink + pathParam;
        }
        if (sortAndEncodeParams != null && !sortAndEncodeParams.equals("")) {
            url = url + "?" + sortAndEncodeParams;
        }
        log.info("发起GET请求 : {}", url);
        Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = response.body().string();
                log.info("成功 - 响应参数 : {}", responseBody);
                return objectMapper.readValue(responseBody, Map.class);
            } else {
                String responseBody = response.body().string();
                log.error("失败 - 响应参数 ：{}", responseBody);
                throw new SecurityException(responseBody);
            }
        } catch (IOException e) {
            log.error("IOException occurred: ", e);
            throw new SecurityException(e.getMessage());
        }
    }

    /**
     * 发送POST请求（不携带token）
     */
    public Map sendNotTokenPost(String apiLink, Object obj, String pathParam) {
        String objectToJson = InterlaceUtils.convertObjectToJson(obj);
        String contentType = "application/json";
        MediaType mediaType = MediaType.parse(contentType);
        RequestBody body = RequestBody.create(mediaType, objectToJson);
        String url = interlaceConfig.getUrl() + apiLink;
        if (pathParam != null && !pathParam.equals("")) {
            url = url + pathParam;
        }
        Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
        log.info("发起POST请求 : {},body: {}", url, objectToJson);
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String responseBody = response.body().string();
                log.info("成功 - 响应参数 : {}", responseBody);
                return objectMapper.readValue(responseBody, Map.class);
            } else {
                String responseBody = response.body().string();
                log.error("失败 - 响应参数 ：{}", responseBody);
                throw new SecurityException(responseBody);
            }
        } catch (IOException e) {
            log.error("IOException occurred: ", e);
            throw new SecurityException(e.getMessage());
        }
    }
}
